package com.kmvc.message.service;

import java.io.StringReader;
import java.util.ArrayList;
import java.util.List;

import javax.xml.parsers.SAXParser;
import javax.xml.parsers.SAXParserFactory;

import org.xml.sax.InputSource;
import org.xml.sax.XMLReader;

import android.annotation.SuppressLint;
import android.app.ActivityManager;
import android.app.Notification;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.app.Service;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Handler;
import android.os.IBinder;
import android.os.PowerManager;
import android.os.PowerManager.WakeLock;
import android.telephony.TelephonyManager;
import android.util.Log;

import com.kmvc.message.R;
import com.kmvc.message.activity.LoginActivity;
import com.kmvc.message.activity.MainTab;
import com.kmvc.message.activity.MessageApplication;
import com.kmvc.message.database.DbHelper;
import com.kmvc.message.entity.StringEntity;
import com.kmvc.message.handler.StringHandler;
import com.kmvc.message.lock.LockMainActivity;
import com.kmvc.message.tools.NetWorkTool;
import com.kmvc.message.tools.WebService;

//import android.widget.Toast;

@SuppressLint("Wakelock")
public class MessageService extends Service {
	// private String phonenumber;
	private Handler handler = new Handler();

	private String message, IMSI, MolNo;
	public static NotificationManager manager;
	private Notification notification;
	private PendingIntent PIntent;
	// private boolean isrunning = false;
	private List<StringEntity> mStringList = new ArrayList<StringEntity>();
	// private AlertDialog al;
	// private AlertDialog.Builder builder;
	// DbHelper dbhelper = new DbHelper(MessageService.this);
	private MessageApplication application = null;

	@Override
	public IBinder onBind(Intent arg0) {
		//
		return null;
	}

	Runnable runnable = new Runnable() {
		public void run() {
			NetWorkTool tool = new NetWorkTool();
			if (tool.isNetwork(MessageService.this)) {
				AccIntent();
				SharedPreferences sp = getSharedPreferences(
						"com.kmvc.message_preferences", 0);
				// Log.e("service66", sp.getInt("time", 5) + "");
				int plindex = Integer.parseInt(sp.getString("pllist", "0"));
				// Log.e("service70", plindex+"");
				int time = 5;
				switch (plindex) {
				case 0:
					time = 5;
					break;
				case 1:
					time = 10;
					break;
				case 2:
					time = 15;
					break;
				case 3:
					time = 20;
					break;
				case 4:
					time = 25;
					break;
				case 5:
					time = 30;
					break;
				case 6:
					time = 35;
					break;
				case 7:
					time = 40;
					break;
				case 8:
					time = 45;
					break;
				case 9:
					time = 50;
					break;
				case 10:
					time = 55;
					break;
				case 11:
					time = 60;
					break;
				default:
					break;
				}
				Log.d("MessageService -->time", time + "");
				handler.postDelayed(runnable, time * 60 * 1000);
			} else {
				// Log.e("kmvc", "no network");
			}

		}
	};

	@Override
	public void onDestroy() {
		//
		// Log.e("destory", "destory");
		// MessageService.isrunning = false;
		Intent intent = new Intent();
		intent.setClass(this, MessageService.class);
		this.startService(intent);
		// Log.e("restar", "restar");

	}

	@SuppressWarnings("deprecation")
	@Override
	public void onStart(Intent intent, int startId) {
		//
		super.onStart(intent, startId);
		application = (MessageApplication) this.getApplication();
		SharedPreferences sp = getSharedPreferences(
				"com.kmvc.message_preferences", 0);
		if (sp.getBoolean("isclear", false) == true) {
			DbHelper dbHelper = new DbHelper(MessageService.this);
			int day = Integer.parseInt(sp.getString("timelist", "-2"));
			if (day > -1) {
				try {
					dbHelper.autodelete(String.valueOf(day));
				} catch (Exception e) {
					e.printStackTrace();
				}

			}
			dbHelper.close();
		}

		Log.d("kmvc", "服务开启");
		TelephonyManager mTelephonyMgr = (TelephonyManager) MessageService.this
				.getSystemService(Context.TELEPHONY_SERVICE);

		try {
			IMSI = mTelephonyMgr.getSubscriberId() + "";
			MolNo = mTelephonyMgr.getDeviceId() + "";
		} catch (Exception e) {
			e.printStackTrace();
		}
		// Toast.makeText(MessageService.this, "服务开启",
		// Toast.LENGTH_LONG).show();
		handler.postDelayed(runnable, 3000);
	}

	@Override
	public void onCreate() {
		//
		super.onCreate();
	}

	Runnable noticeRunnable = new Runnable() {

		@Override
		public void run() {

			MessageService.manager.cancel(0);
		}
	};

	Runnable r = new Runnable() {
		@SuppressWarnings("deprecation")
		@Override
		public void run() {

			if (!message
					.equals("<?xml version='1.0' encoding='UTF-8' standalone='yes' ?>null")
					&& !message
							.equals("<?xml version='1.0' encoding='UTF-8' standalone='yes' ?><data></data>")) {
				Log.d("Message", message);
				DbHelper dbhelper = new DbHelper(MessageService.this);
				try {
					dbhelper.inserthistorybyListnew(mStringList);

				} catch (Exception e) {

				}
				dbhelper.close();
				application.isRefsh = true;
				final Context context = MessageService.this;

				PowerManager pManager = (PowerManager) getSystemService(Context.POWER_SERVICE);
				WakeLock m_wakeObj = (WakeLock) pManager.newWakeLock(
						PowerManager.FULL_WAKE_LOCK
								| PowerManager.ACQUIRE_CAUSES_WAKEUP
								| PowerManager.ON_AFTER_RELEASE, "");

				// 点亮屏幕10秒钟
				m_wakeObj.acquire(1000 * 10);

				ActivityManager am = (ActivityManager) getSystemService(ACTIVITY_SERVICE);
				ComponentName cn = am.getRunningTasks(1).get(0).topActivity;
				String classname = cn.getClassName();
				Log.d("classname", classname);

				// 通知栏
				Intent inte = new Intent(MessageService.this,
						LockMainActivity.class);
				// inte.putExtra("message", message);
				inte.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
				application.isRefsh = true;
				manager = (NotificationManager) context
						.getSystemService(Context.NOTIFICATION_SERVICE);
				PIntent = PendingIntent.getActivity(context, 0, inte, 0);
				notification = new Notification(R.drawable.iconnotice, "新消息",
						System.currentTimeMillis());
				int position = mStringList.size() - 1;
				String info = "";
				String conString = mStringList.get(position).getContent();
				if (conString.startsWith("*html^")) {
					int titlestart = conString.indexOf("*title^") + 7;
					int titleend = conString.indexOf("*/title^");
					try {
						String titleString = conString.substring(titlestart,
								titleend);
						info = titleString;
					} catch (Exception e) {
						//
						e.toString();
					}
				} else {
					try {
						info = conString.substring(0, 20) + " ("
								+ (position + 1) + ")";
					} catch (Exception e) {
						//
						info = conString + " (" + (position + 1) + ")";
					}

				}

				notification.setLatestEventInfo(context, "新消息", info, PIntent);
				notification.flags = Notification.FLAG_AUTO_CANCEL;
				notification.defaults = Notification.DEFAULT_SOUND;// 添加声音提示
				
				// audioStreamType的值必须是AudioManager中的值，代表响铃的模式
				notification.audioStreamType = android.media.AudioManager.ADJUST_LOWER;
				try {
					manager.notify(0, notification);
					
				} catch (Exception e) {
					e.printStackTrace();
				}

				if (!classname.contains("Messageother")
						&& !classname.contains("SlidingActivity")) {

				}
				// else if (classname.contains("MessageGroup")) {
				// // MessageService.manager.cancel(0);
				// handler.postDelayed(noticeRunnable, 3000);
				//
				// Intent intent = new Intent(context, MessageGroup.class);
				// intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
				// context.startActivity(intent);
				//
				// }
				else if (classname.contains("Messageother")) {
					// MessageService.manager.cancel(0);
					handler.postDelayed(noticeRunnable, 3000);
					Intent intent = new Intent(context, MainTab.class);
					intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
					context.startActivity(intent);
				} else if (classname.contains("SlidingActivity")) {
					handler.postDelayed(noticeRunnable, 3000);
					Intent intent = new Intent(context, MainTab.class);
					intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
					context.startActivity(intent);
					// Toast.makeText(context, "新消息", Toast.LENGTH_LONG).show();
				}

			} else {
				Log.d("kmvc", "没读取到数据");
			}
		}
	};

	protected void AccIntent() {

		new Thread() {
			public void run() {
				try {

					final SharedPreferences settingSharedPreferences = getSharedPreferences(
							"phonenumber", 0);
					String tempimsi = settingSharedPreferences.getString(
							"IMSI", "");
					String tempmolno = settingSharedPreferences.getString(
							"MolNo", "");
					if (IMSI.equals(tempimsi) && MolNo.equals(tempmolno)) {
						message = "<?xml version='1.0' encoding='UTF-8' standalone='yes' ?>"
								+ WebService.CDMA(IMSI, MolNo);

						if (!message
								.equals("<?xml version='1.0' encoding='UTF-8' standalone='yes' ?>null")
								&& !message
										.equals("<?xml version='1.0' encoding='UTF-8' standalone='yes' ?><data></data>")) {
							Log.d("Message", message);
							try {
								StringReader read = new StringReader(message);
								InputSource mInputSource = new InputSource(read);
								SAXParserFactory msSaxParserFactory = SAXParserFactory
										.newInstance();
								SAXParser msSaxParser = msSaxParserFactory
										.newSAXParser();
								XMLReader msXmlReader = msSaxParser
										.getXMLReader();
								StringHandler mStringHandler = new StringHandler();
								msXmlReader.setContentHandler(mStringHandler);
								msXmlReader.parse(mInputSource);
								mStringList = mStringHandler.getParsedData();
							} catch (Exception e) {
								e.toString();
							}

						} else {
							// Log.e("kmvc", "没读取到数据");
						}

						handler.post(r);
					} else {

						Intent intent = new Intent(MessageService.this,
								LoginActivity.class);
						intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
						MessageService.this.startActivity(intent);
						MessageService.this.stopSelf();

					}

				} catch (Exception e) {

				}
			}
		}.start();
	}

}
